/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，项目使用请保留此说明
 */
const app = getApp()
let _timer = null;
let isReady = false;
Page({
  data: {
    config: app.globalData.config,
    reportShow: false,
    page: {
      searchCount: false,
      current: 1,
      size: 10
    },
    wxUser: null,
    loadmore: true,
    AlarmList: [],
    border: {
      color: '#f6f6f6',
    },
    popVisible: false,
    isLoading: false,
    deviceList: [],
    selfMain: 2,
    isOne: false,
    roomCondition: {},
    loadingFinish: false,
    fumehood: {},
    disable: false,
    alarmContent: [],
    deviceIds: [],
    isGuest: false,
    originalDeviceList: []
  },
  onLoad() {
    this.setData({
      isLoading: true
    })
    isReady = false
    app.initPage()
      .then(res => {
        let wxUser = app.globalData.wxUser
        this.setData({
          wxUser: wxUser
        })
        if (wxUser == null || wxUser.phone == null) {
          this.setData({
            popVisible: true
          })
          this.data.loadingFinish = true
        } else if (wxUser.sysUser == null) {
          wx.showModal({
            title: '提示',
            content: '系统中没有用户信息，您将以游客方式使用',
            showCancel: false,
            complete: (res) => {
              if (res.cancel) {
              }
              if (res.confirm) {
                this.setData({
                  isGuest: true
                })
                wx.showLoading({
                  title: '数据加载中',
                })
                this.loadData()
              }
            }
          })
          this.data.loadingFinish = true
        } else {
          wx.showLoading({
            title: '数据加载中',
          })
          this.loadData()
        }
        if (this.data.loadingFinish == true) {
          this.setData({
            isLoading: false
          })
          wx.hideLoading()
        }
      })
    let v = wx.getStorageSync('self-main')
    if (v != null && v != '' && v != undefined) {
      this.setData({
        selfMain: v
      })
    }
  },
  onShow() {
    this.refreshData()
  },
  onReady() {
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    if (_timer != null) {
      clearInterval(_timer)
    }
  },
  /*
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (_timer != null) {
      clearInterval(_timer)
    }
  },
  loadData() {
    this.getDevice()
  },
  getDevice: function () {
    app.api.getDevice().then(res => {
      if (res.data != null && res.data instanceof Array) {
        let value = wx.getStorageSync('deviceList')
        if (value == null || value == "" || value == undefined) {
          let _list = []
          for (let i = 1; i < res.data.length + 1; i++) {
            let item = res.data[i - 1]
            if (item != null) {
              _list.push(item)
            }
          }
          this.setData({
            deviceList: _list
          })
        } else {
          let deviceList = JSON.parse(value);
          if (deviceList instanceof Array) {
            let _l = [];
            let _tempList = [];
            for (let i = 0; i < res.data.length; i++) {
              let item = res.data[i]

              if (item != null) {
                let index = _l.length;
                for (let j = 0; j < deviceList.length; j++) {
                  let t = deviceList[j];
                  if (t.deviceId == item.deviceId && t.show == 1) {
                    let obj = item
                    // _l.splice(t.sort - 1, 0, obj)
                    _tempList.push(item)
                  }
                }
                // if (index == _l.length) {
                //   _tempList.push(item)
                // }
              }
            }
            // let newList = _l.concat(_tempList)
            let newList = _tempList
            this.setData({
              deviceList: newList,
              originalDeviceList: res.data
            })
          }
        }
        let fumehoodCount = 0;
        let _index = -1;
        let _alarmContent = []
        let _deviceIds = []
        for (let i = 0; i < this.data.deviceList.length; i++) {
          let item = this.data.deviceList[i]
          if (item != null) {
            _deviceIds.push(item.deviceId)
            if (item.alarmContent.length > 0) {
              _alarmContent.push(item.alarmContent)
            }
            if (item.type == '2') {
              fumehoodCount += 1
              this.setData({
                fumehood: item
              })
              _index = i
            } else if (item.type == '9') {
              this.setData({
                roomCondition: item
              })
            }
          }
        }
          this.setData({
              deviceIds: _deviceIds
          })

          // if (_alarmContent != this.data.alarmContent) {
          this.setData({
              alarmContent: _alarmContent
          })
          // }
          // if (fumehoodCount == 1) {
          //   this.setData({
          //     // isOne: true
          //   })
          //   this.data.deviceList.splice(_index, 1);
          //   let arr = this.data.deviceList;
          //   this.setData({
          //     deviceList: arr
          //   })
          // } else {
          //   this.setData({
          //     isOne: false
          //   })
          // }
      }
      this.setData({
        isLoading: false
      })
      wx.hideLoading()
      isReady = true
    })
  },
  onShareAppMessage: function () {
    let title = '同济能源管理'
    let path = 'pages/home/index'
    return {
      title: title,
      path: path,
      success: function (res) {
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log(res.errMsg)
        }
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  refresh() {
    this.setData({
      loadmore: true,
      ['page.current']: 1,
      AlarmList: [],
    })
  },
  refreshData() {
    let _this = this
    _timer = setInterval(function () {
      if (isReady && _this.data.deviceIds.length > 0) {
        let value = wx.getStorageSync('deviceList')
        if (value != null && value != "" && value != undefined) {
          let deviceList = JSON.parse(value);
          if (deviceList instanceof Array) {
            var ids = 0
            for (let j = 0; j < deviceList.length; j++) {
              let d = deviceList[j]
              if (d.show == 1) {
                ids += 1
              }
            }
            if (ids != _this.data.deviceIds.length) {
              _this.getDevice()
              return
            }
          }
        }
        app.api.getDeviceWx(_this.data.deviceIds).then(res => {
          if (res.data != null && res.data instanceof Array) {
            let tempArray = [];
            for (let i = 0; i < res.data.length; i++) {
              let item_i = res.data[i];
              //如果是单一显示的通风柜，需要处理通风柜数据
              if (_this.data.fumehood != null && _this.data.isOne == true && _this.data.fumehood.device == item_i.deviceId) {
                let d = _this.data.fumehood
                d.airSpeed = item_i.airSpeed
                d.airVolume = item_i.airVolume
                d.windowHeight = item_i.windowHeight
                d.angle = item_i.angle
                d.temperature = item_i.temperature
                d.light = item_i.light
                d.power = item_i.power
                d.force = item_i.force
                d.humidity = item_i.humidity
                d.pressure = item_i.pressure
                d.tvoc = item_i.tvoc
                d.powerConsumption = item_i.powerConsumption
                d.frequency = item_i.frequency
                d.ampere = item_i.ampere
                d.workingMode = item_i.workingMode
                d.isOnline = item_i.isOnline
                d.isBeing = item_i.isBeing
                d.isAutoDoor = item_i.isAutoDoor
                d.alarmContent = item_i.alarmContent
                if (d.power != null) {
                  d.isRunning = d.power
                }
                _this.setData({
                  fumehood: d
                })
                continue;
              }
              for (let j = 0; j < _this.data.deviceList.length; j++) {
                let item_j = _this.data.deviceList[j];
                if (item_j.deviceId == item_i.deviceId) {
                  item_j.airSpeed = item_i.airSpeed
                  item_j.airVolume = item_i.airVolume
                  item_j.windowHeight = item_i.windowHeight
                  item_j.angle = item_i.angle
                  item_j.temperature = item_i.temperature
                  item_j.light = item_i.light
                  item_j.power = item_i.power
                  item_j.force = item_i.force
                  item_j.humidity = item_i.humidity
                  item_j.pressure = item_i.pressure
                  item_j.tvoc = item_i.tvoc
                  item_j.powerConsumption = item_i.powerConsumption
                  item_j.frequency = item_i.frequency
                  item_j.ampere = item_i.ampere
                  item_j.workingMode = item_i.workingMode
                  item_j.isOnline = item_i.isOnline
                  item_j.isBeing = item_i.isBeing
                  item_j.isAutoDoor = item_i.isAutoDoor
                  item_j.alarmContent = item_i.alarmContent

                  if (item_j.power != null) {
                    item_j.isRunning = item_j.power
                  }
                  tempArray.push(item_j)
                  break
                }
              }
            }
            _this.setData({
              deviceList: tempArray
            })
            let _alarmContent = []
            for (let i = 0; i < _this.data.deviceList.length; i++) {
              let item = _this.data.deviceList[i]
              if (item != null) {
                if (item.alarmContent.length > 0) {
                  _alarmContent.push(item.alarmContent)
                }
                for (let j = 0; j < _this.data.originalDeviceList.length; j++) {
                  let obj = _this.data.originalDeviceList[j]
                  if (obj.deviceId == item.deviceId) {
                    item.type = obj.type
                    break;
                  }
                }
                if (item.type == '9') {
                  if (item != null && item.temperature != null && item.tvoc != null) {
                    _this.setData({
                      roomCondition: item
                    })
                  }
                }
              }
            }
            let sameAlarm = true;
            if (_alarmContent.length > 0) {
              for (let i = 0; i < _alarmContent.length; i++) {
                let a = _alarmContent[i];
                let same = false;
                for (let j = 0; j < _this.data.alarmContent.length; j++) {
                  let d = _this.data.alarmContent[j];
                  if (a == d) {
                    same = true;
                    break;
                  }
                }
                if (same === false) {
                  sameAlarm = false
                  break;
                }
              }
            } else {
              sameAlarm = false
            }
            if (sameAlarm === false || _alarmContent.length != _this.data.alarmContent.length) {
              _this.setData({
                alarmContent: _alarmContent
              })
              console.log("refresh", _this.data.alarmContent);
            }
          }
        })
      }
    }, 3000)
  },
  onPullDownRefresh() {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading()
    this.refresh()
    // 隐藏导航栏加载框
    wx.hideNavigationBarLoading()
    // 停止下拉动作
    wx.stopPullDownRefresh()
  },
  onReachBottom() {
    if (this.data.loadmore) {
      this.setData({
        ['page.current']: this.data.page.current + 1
      })
    }
  },
  jumpPage(e) {
    let page = e.currentTarget.dataset.page
    if (page) {
      wx.navigateTo({
        url: page
      })
    }
  },

  showReport() {
    this.setData({
      reportShow: !this.data.reportShow
    })
  },
  oneKeyReport() {
    this.setData({
      reportShow: !this.data.reportShow
    })
    app.api.oneKeyRepair({}).then(res => {
      wx.showToast({
        title: '已经上报',
      })
    })
  },
  reportAdmin() {
    this.setData({
      reportShow: !this.data.reportShow
    })
    wx.makePhoneCall({
      phoneNumber: '13312345678',
    })
  },
  goHomeSetting() {
    wx.navigateTo({
      url: '../home-setting/index',
    })
  },

  closeMakePhone() {
    this.setData({
      popVisible: false
    });
  },
  getPhoneNumber(e) {
    console.log(e.detail.code)
    wx.showLoading({
      title: '处理中',
    })
    var that = this;
    that.closeMakePhone()
    this.setData({
      isLoading: true
    });
    let errMsg = e.detail.errMsg;
    if (errMsg == 'getPhoneNumber:ok') {
      wx.showLoading({
        title: '处理中',
      })
      app.api.getPhoneNumber(wx.getAccountInfoSync().miniProgram.appId, e.detail.code).then(res => {
        if (res.data != null && res.data != "") {
          console.log("解密成功~~~~~~~将解密的号码保存到本地~~~~~~~~");
          let data = res.data;
          let modelId = data.modelId;
          let sn = data.sn;
          let snTicket = data.snTicket;
          var phone = data.phone;
          app.globalData.wxUser.phone = phone
          that.setData({
            wxUser: app.globalData.wxUser,
            sn: sn,
            modelId: modelId,
            snTicket: snTicket
          })
          app.api.wxUserPut(app.globalData.wxUser).then(res => {
            console.log(res)
            if (res.data) {
              if (res.data != null || res.data.sysUser != null) {
                wx.showLoading({
                  title: '数据加载中',
                })
                this.loadData()
              }else if(res.data != null && res.data.sysUser == null){
                wx.showModal({
                  title: '提示',
                  content: '系统中没有用户信息，您将以游客方式使用',
                  showCancel: false,
                  complete: (res) => {
                    if (res.cancel) {
                    }
                    if (res.confirm) {
                      that.setData({
                        isGuest: true
                      })
                      wx.showLoading({
                        title: '数据加载中',
                      })
                      this.loadData()
                    }
                  }
                })
              }
              wx.hideLoading()
            }
          });
        } else {
          wx.showToast({
            title: '获取失败',
            icon: 'error',
            duration: 2000
          })
          that.setData({
            isLoading: false
          })
          wx.hideLoading()
        }
      })
    } else if (errMsg = "fail no permission") {
      wx.hideLoading({
        success: (res) => {
        },
      })
      wx.showToast({
        title: '没有权限',
        icon: 'error',
        duration: 2000
      })
      this.setData({
        isLoading: false
      })
    } else {
      wx.hideLoading({
        success: (res) => {
        },
      })
      wx.showToast({
        title: '获取失败',
        icon: 'error',
        duration: 2000
      })
      this.setData({
        isLoading: false
      })
    }
  },
  goDetail(e) {
    let index = e.currentTarget.dataset.index;
    let value = this.data.deviceList[index];

    if (value.type == '1') {
      wx.navigateTo({
        url: '/pages/lighting/index?deviceId=' + value.deviceId,
      })
    }
    else if (value.type == '2') {
      wx.navigateTo({
        url: '/pages/fumehood/index?deviceId=' + value.deviceId,
      })
    } else if (value.type == '3') {
        wx.navigateTo({
            url: '/pages/fan/index?deviceId=' + value.deviceId,
        })
    } else if (value.type == '6') {
        wx.navigateTo({
            url: '/pages/pure-water/index?deviceId=' + value.deviceId,
        })
    } else if (value.type == '8') {
        wx.navigateTo({
            url: '/pages/gas-path/index?deviceId=' + value.deviceId,
        })
    } else if (value.type == '9') {
        wx.navigateTo({
            url: '/pages/environment/index?deviceId=' + value.deviceId,
        })
    } else if (value.type == '13') {
        wx.navigateTo({
            url: '/pages/dangerous-chemicals/index?deviceId=' + value.deviceId,
        })
    }
  },
  goFumehood() {
    if (this.data.fumehood != null) {
      wx.navigateTo({
        url: '/pages/fumehood/index?deviceId=' + this.data.fumehood.deviceId,
      })
    }
  },
  updateCommand(e) {
    if (this.data.disable) {
      return
    }
    this.data.disable = true
    let key = e.currentTarget.dataset.key;
    let v = this.data.device
    switch (key) {
      case 'light':
        if (v != null)
          if (v.light == null || v.light == '' || v.light == '0') {
            v.light = "1"
            v.commandKey = 'light'
            v.commandValue = '1'
          } else {
            v.light = "0"
            v.commandKey = 'light'
            v.commandValue = '0'
          }
        break;
      case 'power':
        if (v != null)
          if (v.isRunning == null || v.isRunning == '' || v.isRunning == '0') {
            v.isRunning = "1"
            v.commandKey = 'power'
            v.commandValue = '1'
          } else {
            v.isRunning = "0"
            v.commandKey = 'power'
            v.commandValue = '0'
          }
        break;
      case 'force':
        if (v != null)
          if (v.force == null || v.force == '' || v.force == '0') {
            v.force = "1"
            v.commandKey = 'force'
            v.commandValue = '1'
          } else {
            v.force = "0"
            v.commandKey = 'force'
            v.commandValue = '0'
          }
        break;
      case 'mode':
        if (v != null)
          if (v.workingMode == null || v.workingMode == '' || v.workingMode == '0') {
            v.workingMode = "1"
            v.commandKey = 'mode'
            v.commandValue = '1'
          } else {
            v.workingMode = "0"
            v.commandKey = 'mode'
            v.commandValue = '0'
          }
        break;
      case 'door':
        if (v != null)
          if (v.isAutoDoor == null || v.isAutoDoor == '' || v.isAutoDoor == '0') {
            v.isAutoDoor = "1"
            v.commandKey = 'isAutoDoor'
            v.commandValue = '1'
          } else {
            v.isAutoDoor = "0"
            v.commandKey = 'isAutoDoor'
            v.commandValue = '0'
          }
        break;
      case 'repair':
        if (v != null)
          wx.showToast({
            title: '报修信息已经发送！！！',
          })
        break;
    }
    if (_timer != null) {
      clearTimeout(_timer)
    }
    _timer = setTimeout(function () {
      _this.data.disable = false
    }, 1000)
  }
})
